import React, { useEffect, useState, useRef } from "react";
import { Form, Button, Input, message } from "antd";
import { useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router-dom";
import http from "../../utils/http";

import "./index.scss";

export default function PostsShow() {
  const navigate = useNavigate();
  const { id } = useParams();
  const token = useSelector((state) => state.user.token);
  const userId = useSelector((state) => state.user.userId);
  // 存储当前编辑的帖子的详情
  // const [info, setInfo] = useState({});
  const [form] = Form.useForm();
  // const form = useRef();

  async function onFinish(values) {
    try {
      if (id) {
        // 编辑操作
        await http.patch(`/posts/${id}`, {
          title: values.title,
          body: values.body,
        });
        message.success("编辑成功");
        // 后退到列表页面
        navigate(-1);
      } else {
        // 新增操作
        await http.post("/posts", {
          title: values.title,
          body: values.body,
          // 当前登录的用户Id
          userId: userId,
        });
        message.success("新增成功");
        // 后退到列表页面
        navigate(-1);
      }
    } catch (error) {
      message.error(error.message);
    }
  }

  async function getData() {
    try {
      const response = await http.get(`/posts/${id}`);
      // console.log("===", response.data, form);
      // setInfo(response.data);
      // form.setFieldValue("title", "hello");
      // console.log(form.current);
      form.setFieldsValue(response.data);
    } catch (error) {}
  }

  useEffect(() => {
    if (id) {
      getData();
    }
  }, []);

  return (
    <div className="posts-show">
      <h1>{id ? "编辑" : "新增"}帖子</h1>
      {/* 
          info 赋值之后为什么没有显示出来
          Form 组件是一个非受控组件，数据后续的变化不会表单的输入变化
       */}
      <Form form={form} onFinish={onFinish}>
        <Form.Item
          name="title"
          rules={[
            {
              required: true,
              message: "请输入标题",
            },
          ]}
        >
          <Input placeholder="标题" />
        </Form.Item>

        <Form.Item
          name="body"
          rules={[
            {
              required: true,
              message: "请输入正文",
            },
          ]}
        >
          <Input.TextArea rows={4} placeholder="正文" />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            {id ? "编辑" : "新增"}
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
